<template>
  <el-dialog
    :title="
      mode === 'add' ? '新增文档' : mode === 'look' ? '查看文档' : '修改文档'
    "
    v-model="showModel"
    width="920px"
    :before-close="handleClose"
  >
    <div class="content">
      <el-card class="card-box form-box">
        <div>
          <el-row class="form-info" v-if="mode !== 'add'">
            <el-col :span="10" :offset="1">
              创建人: {{ infoState.createUserName }}
            </el-col>
            <el-col :span="10">创建时间: {{ infoState.createTime }}</el-col>
            <!-- <el-col :span="8">文档编号: {{ infoState.billNum }}</el-col> -->
          </el-row>
          <el-form
            ref="formRef"
            :model="formState"
            :rules="Rules"
            label-width="120px"
          >
            <el-form-item
              label="文档名称"
              placeholder="请输入文档名称"
              prop="documentName"
            >
              <el-input
                v-model="formState.documentName"
                :style="{ width: '420px' }"
                disabled
              />
            </el-form-item>
            <el-form-item
              label="文档类型"
              placeholder="请选择文档类型"
              prop="documentTypeCode"
            >
              <el-cascader
                :style="{ width: '420px' }"
                :disabled="!isEdit"
                v-model="formState.documentTypeCode"
                filterable
                :options="documentTypeList"
                :props="documentProp"
                @change="changeType"
                placeholder="输入名称搜索"
              />
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="formState.remarks"
                type="textarea"
                :disabled="!isEdit"
              ></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="上传文档" prop="documentAttachmentArr">
                  <ecm-upload
                    :files="defaultFileList"
                    :disabled="!isEdit"
                    :hideText="!isEdit"
                    :maxLen="1"
                    @set-file="
                      fileList => {
                        handleChange(fileList);
                      }
                    "
                  ></ecm-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-if="isEdit"
          >保存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, defineProps, defineEmits, watch } from "vue";
import NotifMessage from "/@/utils/message/notification";
import ecmUpload from "/@/components/ecmUpload/index.vue";
import * as api from "/@/api/document";
import { postProjectTree } from "/@/api/acceptance";
import { onFilterFileData } from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
const emit = defineEmits(["dialogCallBack"]);

const formRef = ref<HTMLFormElement | null>(null) as any;
const projectInfo = storageLocal.getItem("projectInfo");
const projectManageId = projectInfo?.id || "";

let projectList = ref([]);
let documentTypeList = ref([]);
let projectPhaseList = ref([]);
let detail = ref({});
let formState = reactive({
  documentName: "",
  projectName: "",
  projectManageId: "",
  documentTypeName: null,
  documentTypeCode: "",
  remarks: "",
  documentAttachmentArr: []
});
let showModel = ref(false);
const props = defineProps({
  showDetailDialog: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ""
  },
  mode: {
    type: String,
    default: "add"
  }
});
watch(
  () => props.showDetailDialog,
  newVal => {
    showModel.value = newVal;
    if (newVal && props.mode !== "add") {
      getDetail();
    } else {
      clearDialog();
    }
  }
);

const Rules = {
  // documentName: [
  //   { required: true, message: "请输入文档名称", trigger: "blur" }
  // ],
  projectName: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],
  documentTypeCode: [
    { required: true, message: "请选择文档类型", trigger: "change" }
  ],
  documentAttachmentArr: [
    { required: true, message: "请上传文档", trigger: "change" }
  ]
};

let infoState = reactive({
  createTime: "",
  createUserName: "",
  billNum: ""
});

const documentProp = ref({
  label: "documentTypeName",
  children: "children",
  value: "documentTypeCode",
  emitPath: false
});

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(props.mode)) {
    return true;
  } else {
    return false;
  }
});

const changeType = data => {
  formState.documentTypeCode = data;
  const docObj = getDocTypeAuth(documentTypeList.value, data);
  formState.documentTypeName = docObj.documentTypeName;
};

const getDocTypeAuth = (nodes, searchKey) => {
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].documentTypeCode === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getDocTypeAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
};

let defaultFileList = ref([]);

const handleChange = fileList => {
  defaultFileList.value = fileList;
  formRef.value.clearValidate();
  formState.documentName = fileList.length === 0 ? "" : fileList[0].fileName;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

const clearDialog = () => {
  infoState.createTime = "";
  infoState.createUserName = "";
  infoState.billNum = "";

  formState.documentName = "";
  formState.projectName = "";
  formState.projectManageId = "";
  formState.documentTypeName = null;
  formState.documentTypeCode = "";
  formState.remarks = "";
  formState.documentAttachmentArr = [];

  defaultFileList.value = [];
};

const getDetail = async () => {
  const params = {
    id: props.id
  };
  const { code, data } = await api.fileInfo(params);
  if (code === 200) {
    detail.value = data;
    const {
      createTime,
      createUserName,
      billNum,
      documentName,
      projectName,
      projectManageId,
      documentTypeName,
      documentTypeCode,
      remarks,
      documentAttachmentArr
    } = data;

    infoState.createTime = createTime;
    infoState.createUserName = createUserName;
    infoState.billNum = billNum;

    formState.documentName = documentName;
    formState.projectName = projectName;
    formState.projectManageId = projectManageId;
    formState.documentTypeName = documentTypeName;

    formState.documentTypeCode = documentTypeCode;
    formState.remarks = remarks;
    formState.documentAttachmentArr = documentAttachmentArr;
    defaultFileList.value = onInitFileList(documentAttachmentArr);
  }
};

const handleSubmit = () => {
  formState.documentAttachmentArr = onFilterFileData(defaultFileList.value);
  formRef.value.validate(async (valid: any) => {
    if (!valid) {
      return false;
    }
    if (props.mode === "add") {
      const { code, message } = await api.fileAdd({
        ...formState,
        moduleType: 1,
        projectManageId
      });
      if (code === 200) {
        NotifMessage.success("保存成功");
        emit("dialogCallBack", true);
      } else {
        NotifMessage.error(message);
      }
    } else {
      const params = {
        ...detail.value,
        ...formState,
        id: props.id,
        projectManageId,
        documentAttachment: JSON.stringify(formState.documentAttachmentArr)
      };
      const { code, message } = await api.fileUpdate(params);
      if (code === 200) {
        NotifMessage.success("修改成功");
        emit("dialogCallBack", true);
      } else {
        NotifMessage.error(message);
      }
    }
  });
};

const handleClose = () => {
  emit("dialogCallBack", false);
};
// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectTree({});
    if (code === 200) {
      projectList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 文档类型
const initDoucumentTypeList = async () => {
  const { data } = await api.tDocTypeTree({
    type: projectInfo.projectTypeCode === "A" ? "2" : "3"
  });
  documentTypeList.value = data;
};

// 项目阶段
const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "flow_project_phase"
    };
    const { data } = await api.postDictList(params);
    projectPhaseList.value = data;
  } catch (err) {
    console.log(err);
  }
};

getProjectList();
initDoucumentTypeList();
initProjectPhaseList();
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// .tree-option
.tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// .tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
.tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

.default-option {
  padding: 0 10px;
}
</style>
